package au.com.zonski.gwlite.j2me.client;

import net.jscience.math.kvm.MathFP;

public class BlackHoleController implements Controller 
{
	private int maxSize;
	private int healthPerSize;
	private int maxHealth;
	
	public BlackHoleController( int maxSize, int healthPerSize )
	{
		this.maxSize = maxSize;
		this.healthPerSize = healthPerSize;
		this.maxHealth = maxSize * (healthPerSize + 1) - 1;
	}
	
	public void reset() 
	{

	}

	public boolean update(GWLiteCanvas gameState, GWEntity o) 
	{
		int[] controllerData = (int[]) o.controllerData;
		if( controllerData == null )
		{
			controllerData = initialise( o );
		}
		boolean active = controllerData[3] != 0;
		if( active )
		{
			int size = Math.max( 1, Math.min( this.maxSize-1, controllerData[1] ) ); 
			controllerData[0] = size - 1 + gameState.updateNumber % 3;
			gameState.blackHole = o;
		}
		return false;
	}

	public void learn(GWLiteCanvas gameState) 
	{
		
	}

	public boolean collision(GWLiteCanvas gameState, GWEntity controlled, GWEntity with) 
	{
		int[] controllerData = (int[]) controlled.controllerData;
		if( controllerData == null )
		{
			controllerData = initialise( controlled );
		}
		controllerData[3] = 1;
		int originalHealth = controllerData[2];
		int health = originalHealth;
		switch( with.type )
		{
		case GWEntity.TYPE_BULLET:
			health--;
			break;
		case GWEntity.TYPE_PLAYER:
		case GWEntity.TYPE_SEEKER_CIRCLE:
			break;
		default:
			health++;
			break;
		}
		boolean die = health <= 0;
		boolean explode = health > this.maxHealth;
		if( die )
		{
			gameState.explode( controlled, with.type == GWEntity.TYPE_BULLET );
		}
		else if( explode )
		{
			for( int i=0; i<health; i++ )
			{
				
				GWEntity circle = new GWEntity(
						gameState,
						controlled.x + controlled.width/2 + gameState.random.nextInt() % (controlled.width*2), 
						controlled.y + controlled.height/2 + gameState.random.nextInt() % (controlled.height*2), 
						GWEntity.TYPE_SEEKER_CIRCLE 
				);
				gameState.layers[ GWEntity.TYPE_SEEKER_CIRCLE ].addElement( circle );
			}
			gameState.explode( controlled );
		}
		else if( health != originalHealth )
		{
			int size = health / this.healthPerSize;
			//controllerData[0] = size;
			controllerData[1] = size;
			controllerData[2] = health;
		}
		if( die || explode )
		{
			gameState.blackHole = null;
		}
		return die || explode;
	}
	
	private int[] initialise( GWEntity o )
	{
		int size = this.maxSize/2;
		int health = this.healthPerSize * size;
		int[] controllerData = new int[]{ size, size, health, 0 };
		o.controllerData = controllerData;
		return controllerData;
	}

}
